#include "config.h"
#include "database.h"
#include "log.h"
#include "request.h"
#include "server.h"
#include <stdlib.h>
#include <string.h>

void create_cli_thread(struct request *req);

void handle_request(struct request *req)
{
	
	create_cli_thread(req);
	
}





struct request *accept_request(const int server_fd)
{
	struct request *req;
	int socklen;
	
	req = (struct request *)malloc(sizeof(struct request));	
	if (!req)
		return 0;
	memset(req, 0, sizeof(struct request) );
	
	socklen = sizeof(req->addr);
	
	req->fd = accept(server_fd, (struct sockaddr *) &req->addr,
		&socklen);
	
	if (req->fd == -1) { 
		LOG_ERR("accept faild\n");	
		free_request(req);
		return 0;
	}
	
	return req;
}	

int get_socket();
void close_socket(int fd);
/* failue: -1
*  success: 
*/
int init_server( )
{	
	int rtn;
	int server_fd;
	struct sockaddr_in  my_addr;
	int opt = 1;
	
	server_fd = get_socket();	
	if ( -1 == server_fd ) {
		SYS_ERR("socket");
		LOG_ERR("socket failed\n");
		return BS_ERROR;
	}
	rtn = setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt) );
	if ( -1 == rtn ) {
		LOG_ERR("setsockopt failed\n");
		close_socket(server_fd);
		return BS_ERROR;
	}
	
	my_addr.sin_family=AF_INET;
	my_addr.sin_port=htons(PORT);
	my_addr.sin_addr.s_addr = INADDR_ANY;
	
	rtn = bind(server_fd, (struct sockaddr *) &my_addr,
		sizeof(struct sockaddr_in)); 
	if ( -1 == rtn ) {
		LOG_ERR("bind faild\n");
		close_socket(server_fd);
		return BS_ERROR;
	}
	
	rtn = listen(server_fd, LISTEN_BACKLOG); 
	if ( -1 == rtn ) {
		LOG_ERR("listen failed\n");
		close_socket(server_fd);
		return BS_ERROR;
	}
	
	LOG_DEBUG("listen port: %d\n", PORT);
	
	return server_fd;
	
}	


